package com.syni.mdd.sjb.community.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syni.mdd.sjb.common.component.utils.common.utils.RpcResponseVo;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddAll.apiBusinessAuth.GetBusinessAuthByLicenseNameDto;
import com.syni.mdd.sjb.common.component.utils.feign.service.mddAll.BusinessAuthRestService;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.WxCorpBusinessRelation;
import com.syni.mdd.sjb.common.component.mybatis.community.mapper.WxCorpBusinessRelationMapper;
import com.syni.mdd.sjb.community.base.service.WxCorpBusinessRelationService;
import com.syni.mdd.sjb.community.base.service.WxPermanentCodeService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lcc
 * @since 2020-07-24
 */
@Log4j2
@Service
public class WxCorpBusinessRelationServiceImpl extends ServiceImpl<WxCorpBusinessRelationMapper, WxCorpBusinessRelation> implements WxCorpBusinessRelationService {
    @Autowired
    WxCorpBusinessRelationMapper wxCorpBusinessRelationMapper;

    @Autowired
    WxPermanentCodeService wxPermanentCodeService;

    @Autowired
    BusinessAuthRestService businessAuthRestService;

    @Override
    public synchronized void handleCorpBusinessAuthReleation(String corpId) {
        try {
            String cropData = wxPermanentCodeService.getCropDataByCropId(corpId);
            if(StringUtils.isNotBlank(cropData)) {
                JSONObject jsonObject = JSON.parseObject(cropData);
                log.info("handleCorpBusinessAuthReleation : " + jsonObject.toJSONString());
                if (jsonObject.containsKey("auth_corp_info")) {
                    JSONObject authCorpInfo = jsonObject.getJSONObject("auth_corp_info");
                    String corpFullName = authCorpInfo.getString("corp_full_name");
                    if(StringUtils.isBlank(corpFullName)){
                        corpFullName = authCorpInfo.getString("corp_name");
                    }
                    if (StringUtils.isNotBlank(corpFullName)) {
                        RpcResponseVo rpcResponseVo = businessAuthRestService.getBusinessAuthByLicenseName(corpFullName);
                        if (rpcResponseVo.isSuccess()) {
                            List<GetBusinessAuthByLicenseNameDto> getBusinessAuthByLicenseNameDtos = rpcResponseVo.parseArray(GetBusinessAuthByLicenseNameDto.class);
                            if (CollectionUtils.isNotEmpty(getBusinessAuthByLicenseNameDtos)) {
                                List<WxCorpBusinessRelation> wxCorpBusinessRelations = new ArrayList<>();
                                getBusinessAuthByLicenseNameDtos.forEach(gd -> {
                                    WxCorpBusinessRelation wxCorpBusinessRelation = new WxCorpBusinessRelation();
                                    wxCorpBusinessRelation.setCorpid(corpId);
                                    wxCorpBusinessRelation.setBusinessAuthId(gd.getId());
                                    wxCorpBusinessRelation.setNewTime(LocalDateTime.now());
                                    wxCorpBusinessRelations.add(wxCorpBusinessRelation);
                                });
                                if (wxCorpBusinessRelations.size() > 0) {
                                    QueryWrapper queryWrapper = new QueryWrapper();
                                    queryWrapper.eq(WxCorpBusinessRelation.CORPID, corpId);
                                    List<WxCorpBusinessRelation> exist = wxCorpBusinessRelationMapper.selectList(queryWrapper);
                                    if (CollectionUtils.isNotEmpty(exist)) {
                                        this.removeByIds(exist.stream().map(WxCorpBusinessRelation::getId).collect(Collectors.toSet()));
                                    }
                                    this.saveBatch(wxCorpBusinessRelations);
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }

    public synchronized boolean handleCorpBusinessAuthReleationByPhone(String corpId,String phone) {
        try {
            String cropData = wxPermanentCodeService.getCropDataByCropId(corpId);
            if(StringUtils.isNotBlank(cropData)) {
                JSONObject jsonObject = JSON.parseObject(cropData);
                log.info("handleCorpBusinessAuthReleation : " + jsonObject.toJSONString());
                if (jsonObject.containsKey("auth_corp_info")) {
                    JSONObject authCorpInfo = jsonObject.getJSONObject("auth_corp_info");
                    String corpFullName = authCorpInfo.getString("corp_full_name");
                    if (StringUtils.isBlank(corpFullName)) {
                        corpFullName = authCorpInfo.getString("corp_name");
                    }
                    if(StringUtils.isNotBlank(corpFullName)) {
                        RpcResponseVo rpcResponseVo = businessAuthRestService.getBusinessAuthByLicenseNameAndPhone(corpFullName, phone);
                        if (rpcResponseVo.isSuccess()) {
                            List<GetBusinessAuthByLicenseNameDto> getBusinessAuthByLicenseNameDtos = rpcResponseVo.parseArray(GetBusinessAuthByLicenseNameDto.class);
                            if (CollectionUtils.isNotEmpty(getBusinessAuthByLicenseNameDtos)) {
                                List<WxCorpBusinessRelation> wxCorpBusinessRelations = new ArrayList<>();
                                getBusinessAuthByLicenseNameDtos.forEach(gd -> {
                                    WxCorpBusinessRelation wxCorpBusinessRelation = new WxCorpBusinessRelation();
                                    wxCorpBusinessRelation.setCorpid(corpId);
                                    wxCorpBusinessRelation.setBusinessAuthId(gd.getId());
                                    wxCorpBusinessRelation.setNewTime(LocalDateTime.now());
                                    wxCorpBusinessRelations.add(wxCorpBusinessRelation);
                                });
                                if (wxCorpBusinessRelations.size() > 0) {
                                    QueryWrapper queryWrapper = new QueryWrapper();
                                    queryWrapper.eq(WxCorpBusinessRelation.CORPID, corpId);
                                    List<WxCorpBusinessRelation> exist = wxCorpBusinessRelationMapper.selectList(queryWrapper);
                                    if (CollectionUtils.isNotEmpty(exist)) {
                                        this.removeByIds(exist.stream().map(WxCorpBusinessRelation::getId).collect(Collectors.toSet()));
                                    }
                                    this.saveBatch(wxCorpBusinessRelations);
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return false;
    }

    @Override
    public List<WxCorpBusinessRelation> findCorpBusinessRelationBy(Set<Integer> authIds) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in(WxCorpBusinessRelation.BUSINESS_AUTH_ID,authIds);
        List<WxCorpBusinessRelation> wxCorpBusinessRelations = this.list(queryWrapper);
        return wxCorpBusinessRelations;
    }
}
